package org.halk.file;

import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

import java.io.File;

public class FileMonitorExample {

    public static void main(String[] args) throws Exception {

        // 创建要监听的目录
        File directory = new File("D:/path");

        // 创建文件变化监听器
        FileAlterationObserver observer = new FileAlterationObserver(directory);
        observer.addListener(new FileAlterationListener() {

            @Override
            public void onStart(FileAlterationObserver observer) {
                System.out.println("监听器开始工作");
            }

            @Override
            public void onDirectoryCreate(File directory) {
                System.out.println("目录创建：" + directory.getAbsolutePath());
            }

            @Override
            public void onDirectoryChange(File directory) {
                System.out.println("目录修改：" + directory.getAbsolutePath());
            }

            @Override
            public void onDirectoryDelete(File directory) {
                System.out.println("目录删除：" + directory.getAbsolutePath());
            }

            @Override
            public void onFileCreate(File file) {
                System.out.println("文件创建：" + file.getAbsolutePath());
            }

            @Override
            public void onFileChange(File file) {
                System.out.println("文件修改：" + file.getAbsolutePath());
            }

            @Override
            public void onFileDelete(File file) {
                System.out.println("文件删除：" + file.getAbsolutePath());
            }

            @Override
            public void onStop(FileAlterationObserver observer) {
                System.out.println("监听器停止工作");
            }
        });

        // 创建文件变化监控器，每隔5秒钟扫描一次目录
        FileAlterationMonitor monitor = new FileAlterationMonitor(5000);
        monitor.addObserver(observer);

        // 启动文件变化监控器
        monitor.start();

        // 监听器会在后台线程中运行，这里可以做其他的事情
        Thread.sleep(600000);

        // 停止文件变化监控器
        monitor.stop();
    }

}
